package com.oanda.blackberry.net;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class UrlEncoder {
    public static String encode(String s, String enc) throws IOException {
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DataOutputStream dOut = new DataOutputStream(bOut);
        StringBuffer ret = new StringBuffer();
        dOut.writeUTF(s);
        ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray());
        bIn.read();
        bIn.read();
        int c = bIn.read();
        while (c >= 0) {
            if (((c >= 97) && (c <= 122)) || ((c >= 65) && (c <= 90)) || ((c >= 48) && (c <= 57))
                    || (c == 46) || (c == 45) || (c == 42) || (c == 95)) {
                ret.append((char) c);
            } else if (c == 32) {
                ret.append('+');
            } else if (c < 128) {
                appendHex(c, ret);
            } else if (c < 224) {
                appendHex(c, ret);
                appendHex(bIn.read(), ret);
            } else if (c < 240) {
                appendHex(c, ret);
                appendHex(bIn.read(), ret);
                appendHex(bIn.read(), ret);
            }

            c = bIn.read();
        }
        return ret.toString();
    }

    private static void appendHex(int arg0, StringBuffer buff) {
        buff.append('%');
        if (arg0 < 16) {
            buff.append('0');
        }

        buff.append(Integer.toHexString(arg0).toUpperCase());
    }
}
